package mytest.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import mytest.util.CheckAddToModel;
import mytest.util.RequestUtil;
import mytest.util.Response;
import test.runner.RunTest;
import test.service.ServiceTestCase;
import test.service.ServiceTestModel;
import test.service.ServiceUser;
import test.testcase.TestCase;
import test.testcase.TestModel;
import test.testcase.dao.TestCaseDao;
import test.testcase.dao.TestModelDao;
import test.user.user;
import test.utils.GetValue;
import test.utils.JsonResult;

@Controller @RequestMapping(value = "/testcase", produces = "application/json; charset=utf-8")
@CrossOrigin
public class testcase {
	
	private static Logger logger = Logger.getLogger(testcase.class);
	
	@RequestMapping(value = "/gettestcaselist")
	public @ResponseBody String getTestCaseListWithOption(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");  
		int start = RequestUtil.getStartPage(request);
		int end = RequestUtil.getEndPage(request);
		String caseid = request.getParameter("caseid");
		String casename = request.getParameter("casename");
		String channel = request.getParameter("channel");
		String projectid = RequestUtil.getProjectId(request);
		StringBuffer where = new StringBuffer();
		if (!"ALL".equals(caseid) && caseid != null) {
			where.append(" and a.id="+caseid);
		}
		if (!"ALL".equals(casename) && casename != null) {
			where.append(" and a.casename like '%"+casename+"%'");
		}
		if(!"ALL".equals(channel) && channel != null) {
			where.append(" and a.channel='"+channel+"'");
		}
		where.append(" and a.projectid="+projectid);
		logger.info(where.toString());
		return TestCaseDao.getTestcaseList(start, end, where.toString()).toResponse();
	}
	
	@RequestMapping(value = "/getfailtestcaselist")
	public @ResponseBody String getFailTestCaseListWithOption(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");  
		int start = RequestUtil.getStartPage(request);
		int end = RequestUtil.getEndPage(request);
		String caseid = request.getParameter("caseid");
		String casename = request.getParameter("casename");
		String channel = request.getParameter("channel");
		String projectid = RequestUtil.getProjectId(request);
		StringBuffer where = new StringBuffer();
		if (!"ALL".equals(caseid) && caseid != null) {
			where.append(" and a.id="+caseid);
		}
		if (!"ALL".equals(casename) && casename != null) {
			where.append(" and a.casename like '%"+casename+"%'");
		}
		if(!"ALL".equals(channel) && channel != null) {
			where.append(" and a.channel='"+channel+"'");
		}
		where.append(" and a.projectid="+projectid);
		where.append(" and a.last_excute_result in ('失败','异常')");
		logger.info(where.toString());
		return TestCaseDao.getTestcaseList(start, end, where.toString()).toResponse();
	}
	
	@RequestMapping(value = "/gettestmodellist")
	public @ResponseBody String gettestmodellist(HttpServletRequest request) {
		int start = RequestUtil.getStartPage(request);
		int end = RequestUtil.getEndPage(request);
		return TestModelDao.getTestmodelList(start, end, RequestUtil.getProjectId(request)).toResponse();
	}
	
	@RequestMapping(value = "/deltestcase/{id}")
	public @ResponseBody String delTestCase(@PathVariable String id) {
		if (ServiceTestCase.isJobContainCase(id)) {
			Response response = new Response();
			response.setRetCodeFalse();
			response.setRetMessage("不能删除，因为有任务关联");
			return response.toString();
		}
		return TestCaseDao.delTestCase(id).toResponse();
	}
	
	@RequestMapping(value = "/deltestmodel/{id}")
	public @ResponseBody String delTestModel(@PathVariable String id) {
		if (ServiceTestModel.isUsedTestModel(id)) {
			Response response = new Response();
			response.setRetCodeFalse();
			response.setRetMessage("不能删除，因为有用例关联");
			return response.toString();
		}
		return TestModelDao.delTestModel(id).toResponse();
	}
	
	@RequestMapping(value = "/copytestcase/{id}")
	public @ResponseBody String copytestcase(@PathVariable String id) {
		return ServiceTestCase.copyCase(id).toResponse();
	}
	
	@RequestMapping(value = "/copytestcasetomodel/{id}")
	public @ResponseBody String copytestcasetomodel(@PathVariable String id) {
		JsonResult result = ServiceTestCase.copyCaseToModel(id);
		if (result == null) {
			Response response = new Response();
			return response.setFalse("用例不能被转化").toString();
		}
		return result.toResponse();
	}
	
	@RequestMapping(value = "/testcaseinfo/{id}", method = RequestMethod.GET)
	public @ResponseBody String getTestCase(@PathVariable String id) {
		return TestCaseDao.getTestCaseInfo(id).toResponse();
	}
	
	@RequestMapping(value = "/testmodel/{id}")
	public @ResponseBody String getTestModel(@PathVariable String id) {
		return TestModelDao.getTestModelInfo(id).toResponse();
	}
	
	@RequestMapping(value = "/save/{id}", method = RequestMethod.POST)
	public @ResponseBody String saveTestCase(@RequestBody String body, @PathVariable String id) throws UnsupportedEncodingException {
		TestCase testcase = new TestCase();
		JsonResult result = JsonResult.parse(URLDecoder.decode(body, "UTF-8"));
		testcase.setCaseinfo(result.read("desc").toString());
		testcase.setCasename(result.read("casename").toString());
		String priority = result.read("priority").toString();
		testcase.setPriority(priority);
		testcase.setChannel(result.read("channel").toString());
		testcase.setTypetag(result.read("typetag").toString());
		String priorityname = "低";
		if (priority.equals("1")) {
			priorityname = "高";
		}else if (priority.equals("2")) {
			priorityname = "中";
		}
		testcase.setPriorityname(priorityname);
		//判断是否是个合法的testdata用例数据
		if (!ServiceTestCase.isTestData(result.read("testdata").toString())) {
			Response response = new Response();
			response.setRetCodeFalse();
			response.setRetMessage("用例数据不合法，请检查");
			return response.toString();
		}
		return TestCaseDao.updateCaseInfo(id, testcase, result.read("testdata").toString()).toResponse();
	}
	
	@RequestMapping(value = "/model/save/{id}", method = RequestMethod.POST)
	public @ResponseBody String saveTestModel(@RequestBody String body, @PathVariable String id, HttpServletRequest request) throws UnsupportedEncodingException {
		TestModel model = new TestModel();
		JsonResult result = JsonResult.parse(URLDecoder.decode(body, "UTF-8"));
		model.setContent(result.read("desc").toString());
		model.setModelname(result.read("modelname").toString());
		model.setProjectid(RequestUtil.getProjectId(request));
		return TestModelDao.updateModelInfo(id, model).toResponse();
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody String addTestCase(@RequestBody String body, HttpServletRequest request) throws UnsupportedEncodingException {
		TestCase testcase = new TestCase();
		JsonResult result = JsonResult.parse(URLDecoder.decode(body, "UTF-8"));
		testcase.setCaseinfo(result.read("desc").toString());
		testcase.setCasename(result.read("casename").toString());
		String priority = result.read("priority").toString();
		testcase.setPriority(priority);
		testcase.setProjectid(RequestUtil.getProjectId(request));
		testcase.setUserid(RequestUtil.getUserId(request));
		testcase.setChannel(result.read("channel").toString());
		testcase.setTypetag(result.read("typetag").toString());
		String priorityname = "低";
		if (priority.equals("1")) {
			priorityname = "高";
		}else if (priority.equals("2")) {
			priorityname = "中";
		}
		testcase.setPriorityname(priorityname);
		
		//判断是否是个合法的testdata用例数据
		if (!ServiceTestCase.isTestData(result.read("testdata").toString())) {
			Response response = new Response();
			response.setRetCodeFalse();
			response.setRetMessage("用例数据不合法，请检查");
			return response.toString();
		}		
		return TestCaseDao.saveTestCase(testcase, result.read("testdata").toString()).toResponse();
	}
	
	@RequestMapping(value = "/model/add", method = RequestMethod.POST)
	public @ResponseBody String addTestModel(@RequestBody String body, HttpServletRequest request) throws UnsupportedEncodingException {
		TestModel model = new TestModel();
		JsonResult result = JsonResult.parse(URLDecoder.decode(body, "UTF-8"));
		model.setContent(result.read("desc").toString());
		model.setModelname(result.read("modelname").toString());
		model.setProjectid(RequestUtil.getProjectId(request));
		model.setUserid(RequestUtil.getUserId(request));
		return TestModelDao.saveTestModel(model).toResponse();
	}
	
	@RequestMapping(value = "/getcasestep/{id}")
	public @ResponseBody String getTestCaseStep(@PathVariable String id) {
		return TestCaseDao.getTestSteps(id).toResponse();
	}
	
	@RequestMapping(value = "/getmodelstep/{id}")
	public @ResponseBody String getModelStep(@PathVariable String id) {
		return TestModelDao.getTestModelSteps(id).toResponse();
	}
	
	@RequestMapping(value = "/delteststep/{id}")
	public @ResponseBody String delTestCaseStep(@PathVariable String id) {
		return TestCaseDao.delTestCaseStep(id).toResponse();
	}
	
	@RequestMapping(value = "/delmodelstep/{id}")
	public @ResponseBody String delTestModelStep(@PathVariable String id) {
		JsonResult result = TestModelDao.delTestModelStep(id);
		if (result == null) {
			Response response = new Response();
			response.setRetCodeFalse();
			response.setRetMessage("不能删除，因为有用例或其他模型依赖");
			return response.toString();
		}
		return result.toResponse();
	}
	
	@RequestMapping(value = "/excute/{id}", method = RequestMethod.GET)
    public @ResponseBody String excuteTestCase(@PathVariable String id, HttpServletRequest request) {
		user user = ServiceUser.getUserByUserName(RequestUtil.getUserName(request));
		boolean tem = ServiceTestCase.isTestCaseExcuting(ServiceTestCase.getTestCase(id), user);
		Response response = new Response();
		if (tem) {
			response.setRetCodeFalse();
			response.setRetMessage("正在执行，请稍候");
			return response.toString();
		}
		TestCaseDao.addTestCaseExcuteJob(ServiceTestCase.getTestCase(id), user);
		return response.toString();
	}
	
	@RequestMapping(value = "/model/excute/{id}", method = RequestMethod.GET)
    public @ResponseBody String excuteTestModel(@PathVariable String id, HttpServletRequest request) {
		user user = ServiceUser.getUserByUserName(RequestUtil.getUserName(request));
		boolean tem = ServiceTestModel.isTestModelExcuting(id, user);
		Response response = new Response();
		if (tem) {
			response.setRetCodeFalse();
			response.setRetMessage("正在执行，请稍候");
			return response.toString();
		}
		TestModelDao.addTestModelExcuteJob(id, user);
		return response.toString();
	}
	
	@RequestMapping(value = "/excute/status/{id}", method = RequestMethod.GET)
    public @ResponseBody String excuteStatus(@PathVariable String id, HttpServletRequest request) {
		return TestCaseDao.getTestCaseExcuteStatus(id, RequestUtil.getUserId(request)).toResponse();
	}
	
	@RequestMapping(value = "/model/excute/status/{id}", method = RequestMethod.GET)
    public @ResponseBody String excuteModelStatus(@PathVariable String id, HttpServletRequest request) {
		return TestModelDao.getTestModelExcuteStatus(id, RequestUtil.getUserId(request)).toResponse();
	}
	
	@RequestMapping(value = "/excute/log/{id}/{id1}", method = RequestMethod.GET)
    public @ResponseBody String excuteLog(@PathVariable String id, HttpServletRequest request, @PathVariable String id1) {
		String key = id+"_"+RequestUtil.getUserId(request);
		Response response = new Response();
//		response.setList(RunTest.getLogs().get(key));
		List<HashMap<Object, Object>> list = new ArrayList<HashMap<Object,Object>>();
		for(int i=0;i<RunTest.getLogs().get(key).size();i++) {
			HashMap<Object, Object> map = new HashMap<>();
			map.put("log", RunTest.getLogs().get(key).get(i));
			list.add(map);
		}
		response.setList(list);
		return response.toString();
	}
	
	@RequestMapping(value = "/model/excute/log/{id}", method = RequestMethod.GET)
    public @ResponseBody String excuteModelLog(@PathVariable String id, HttpServletRequest request) {
		return ServiceTestModel.getTestModelExcuteLog(id, RequestUtil.getUserId(request));
	}
	
	@RequestMapping(value = "/{id}/addstep", method = RequestMethod.POST)
	@CrossOrigin
	public @ResponseBody String addrequeststep(@RequestBody String body, @PathVariable String id, HttpServletRequest request) {
		user user = RequestUtil.getUser(request);
		boolean tem = ServiceTestCase.addTestCaseRequestStep(new JSONObject(body), GetValue.getParamsByLR(body, "\"testdata\":\"", "\",\"xuanqufa"), id, user.getUserid());
		Response response = new Response();
		if (tem) {
			response.setRetMessage("添加成功");
			return response.toString();
		}else {
			response.setRetCodeFalse();
			response.setRetMessage("添加失败");
			return response.toString();
		}
	}
	
	@RequestMapping(value = "/{id}/addmodelstep", method = RequestMethod.POST)
	@CrossOrigin
	public @ResponseBody String addModelRequeststep(@RequestBody String body, HttpServletRequest request, @PathVariable String id) {
		boolean tem = ServiceTestModel.addModelRequestStep(new JSONObject(body), GetValue.getParamsByLR(body, "\"testdata\":\"", "\",\"xuanqufa"), id, RequestUtil.getUserId(request));
		Response response = new Response();
		if (tem) {
			response.setRetMessage("添加成功");
			return response.toString();
		}else {
			response.setRetCodeFalse();
			response.setRetMessage("添加失败");
			return response.toString();
		}
	}
	
	@RequestMapping(value = "/stepinfo/{id}", method = RequestMethod.GET)
	@CrossOrigin
	public @ResponseBody String getRequeststep(@PathVariable String id) {
		JsonResult result = TestCaseDao.getTestStepParamById(id);
		JSONObject object = TestCaseDao.getTestCaseStepInfo(id).read("data[0]").toJsonObject();
		for(int i=1;i<=5;i++) {
			JSONObject object2 = result.read("data["+(i-1)+"]").toJsonObject();
			if (object2 == null) {
				object.put("paramname"+i, "");
				object.put("rule"+i, "");
				object.put("xuanqufangshi"+i, "");
			}else {
				object.put("paramname"+i, object2.getString("paramname"));
				object.put("rule"+i, object2.getString("expression"));
				object.put("xuanqufangshi"+i, object2.getString("method"));
			}
		}
		result = TestCaseDao.getTestStepAssertById(id);
		for(int i=1;i<=5;i++) {
			JSONObject object2 = result.read("data["+(i-1)+"]").toJsonObject();
			if (object2 == null) {
				object.put("assert"+i, "");
			}else {
				object.put("assert"+i, object2.getString("expression"));
			}
		}
		Response response = new Response();
		response.setRetMessage("查询成功");
		JSONObject re = new JSONObject(response.toString());
		re.put("data", object.toMap());
		return re.toString();	
	}
	
	@RequestMapping(value = "/modelstepinfo/{id}", method = RequestMethod.GET)
	@CrossOrigin
	public @ResponseBody String getModelRequeststep(@PathVariable String id) {
		JsonResult result = TestModelDao.getTestStepParamByModelStepId(id);
		JSONObject object = TestModelDao.getTestModelStepInfo(id).read("data[0]").toJsonObject();
		for(int i=1;i<=5;i++) {
			JSONObject object2 = result.read("data["+(i-1)+"]").toJsonObject();
			if (object2 == null) {
				object.put("paramname"+i, "");
				object.put("rule"+i, "");
				object.put("xuanqufangshi"+i, "");
			}else {
				object.put("paramname"+i, object2.getString("paramname"));
				object.put("rule"+i, object2.getString("expression"));
				object.put("xuanqufangshi"+i, object2.getString("method"));
			}
		}
		result = TestModelDao.getTestModelStepAssertById(id);
		for(int i=1;i<=5;i++) {
			JSONObject object2 = result.read("data["+(i-1)+"]").toJsonObject();
			if (object2 == null) {
				object.put("assert"+i, "");
			}else {
				object.put("assert"+i, object2.getString("expression"));
			}
		}
		Response response = new Response();
		response.setRetMessage("查询成功");
		JSONObject re = new JSONObject(response.toString());
		re.put("data", object.toMap());
		return re.toString();	
	}
	
	@RequestMapping(value = "/{id}/savestep", method = RequestMethod.POST)
	@CrossOrigin
	public @ResponseBody String saveRequeststep(@RequestBody String body, @PathVariable String id, HttpServletRequest request) {
		boolean tem = ServiceTestCase.saveTestCaseRequestStep(new JSONObject(body.replace("\\", "\\\\\\")), GetValue.getParamsByLR(body, "\"testdata\":\"", "\",\"xuanqufa"), id, RequestUtil.getUserId(request));
		Response response = new Response();
		if (tem) {
			response.setRetMessage("保存成功");
			return response.toString();
		}else {
			response.setRetCodeFalse();
			response.setRetMessage("保存失败");
			return response.toString();
		}
	}
	
//	@RequestMapping(value = "/{id}/savestep", method = RequestMethod.POST)
//	@CrossOrigin
//	public @ResponseBody String saveStep(@RequestBody String body, @PathVariable String id) {
//		JsonResult result = JsonResult.parse(body);
//		return TestCaseDao.saveStepName(id, result.read("stepname").toString()).toResponse();
//	}
	
	@RequestMapping(value = "/{id}/savemodelstep", method = RequestMethod.POST)
	@CrossOrigin
	public @ResponseBody String saveModelRequeststep(@RequestBody String body, @PathVariable String id, HttpServletRequest request) {
		boolean tem = ServiceTestModel.saveTestModelRequestStep(new JSONObject(body.replace("\\", "\\\\\\")), GetValue.getParamsByLR(body, "\"testdata\":\"", "\",\"xuanqufa"), id, RequestUtil.getUserId(request));
		Response response = new Response();
		if (tem) {
			response.setRetMessage("保存成功");
			return response.toString();
		}else {
			response.setRetCodeFalse();
			response.setRetMessage("保存失败");
			return response.toString();
		}
	}
	
	@RequestMapping(value = "/model/{modelid}/addmodel", method = RequestMethod.POST)
	@CrossOrigin
	public @ResponseBody String saveModelformodel(@RequestBody String body, @PathVariable String modelid) {
		JSONArray array = new JSONArray(body);
		CheckAddToModel checkAddToModel = new CheckAddToModel(modelid);
		//检查售后有死循环
		if (checkAddToModel.canAddToModel(array.getJSONObject(0).getString("id"))) {
			return TestModelDao.addmodelformodel(modelid, array.getJSONObject(0).getString("id")).toResponse();
		}
		Response response = new Response(); 
		response.setRetCodeFalse();
		response.setRetMessage("不能添加，因为死循环");
		return response.toString();
	}
	
	@RequestMapping(value = "/case/{caseid}/addmodel", method = RequestMethod.POST)
	@CrossOrigin
	public @ResponseBody String saveModelforcase(@RequestBody String body, @PathVariable String caseid) {
		JSONArray array = new JSONArray(body);
		return TestCaseDao.addmodelforcase(caseid, array.getJSONObject(0).getString("modelname"), array.getJSONObject(0).getString("id"), ServiceTestCase.getOrderNum(caseid)+"").toResponse();
	}
	
	@RequestMapping(value = "/teststep/up/{id}", method = RequestMethod.GET)
	@CrossOrigin
	public @ResponseBody String stepup(@PathVariable String id) {
		JsonResult result = TestCaseDao.stepup(id);
		if (result == null) {
			Response response = new Response(); 
			response.setRetCodeFalse();
			response.setRetMessage("不能移动");
			return response.toString();
		}
		return result.toResponse();
	}
	
	@RequestMapping(value = "/teststep/down/{id}", method = RequestMethod.GET)
	@CrossOrigin
	public @ResponseBody String stepdown(@PathVariable String id) {
		JsonResult result = TestCaseDao.stepdown(id);
		if (result == null) {
			Response response = new Response(); 
			response.setRetCodeFalse();
			response.setRetMessage("不能移动");
			return response.toString();
		}
		return result.toResponse();
	}
	
	@RequestMapping(value = "/modelstep/up/{id}", method = RequestMethod.GET)
	@CrossOrigin
	public @ResponseBody String modelstepup(@PathVariable String id) {
		JsonResult result = TestModelDao.modelstepup(id);
		if (result == null) {
			Response response = new Response(); 
			response.setRetCodeFalse();
			response.setRetMessage("不能移动");
			return response.toString();
		}
		return result.toResponse();
	}
	
	@RequestMapping(value = "/modelstep/down/{id}", method = RequestMethod.GET)
	@CrossOrigin
	public @ResponseBody String modelstepdown(@PathVariable String id) {
		JsonResult result = TestModelDao.modelstepdown(id);
		if (result == null) {
			Response response = new Response(); 
			response.setRetCodeFalse();
			response.setRetMessage("不能移动");
			return response.toString();
		}
		return result.toResponse();
	}
	
}
